﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;

namespace WebApiDemo
{
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 统一对调用异常信息进行处理，返回自定义的异常信息
        /// </summary>
        /// <param name="context">HTTP上下文对象</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            //自定义异常的处理
            if (context.Exception is CustomException)
            {
                var exception = (CustomException)context.Exception;
                ResponseApi<object> result = new ResponseApi<object>()
                {
                    code = exception.GetErrorCode(),
                    msg = exception.Message
                };
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    //封装处理异常信息，返回指定JSON对象
                    Content = new StringContent(JsonConvert.SerializeObject(result),
                    Encoding.GetEncoding("UTF-8"), "application/json"),
                    ReasonPhrase = "InternalServerErrorException",
                });
            }
            else
            {
                ResponseApi<object> result = new ResponseApi<object>()
                {
                    code = -1,
                    msg = context.Exception.Message
                };
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    //封装处理异常信息，返回指定JSON对象
                    Content = new StringContent(JsonConvert.SerializeObject(result)),
                    ReasonPhrase = "InternalServerErrorException"
                });
            }
        }
    }

}